package com.lzy.shops.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzy.shops.form.GoodsParams;
import com.lzy.shops.service.OrderService;
import com.lzy.shops.service.PayService;
import com.lzy.shops.utils.OrderUtil;
import com.lzy.shops.utils.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/zfb")
public class PayController {

    @Autowired
    private PayService service;

    ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private OrderService orderService;

    @PostMapping("/pay")
    public Object pay(@RequestBody Map<String, Object> maps) throws JsonProcessingException {
        ResponseData<Object> responseData = null;
        try {
            String goBuy = (String) maps.get("goBuy"); // 区分直接购买和购物车购买
            String user_id = (String) maps.get("user_id");
            String info = (String) maps.get("info");
            Integer money = (Integer) maps.get("money");
            String payment_type = (String) maps.get("payment_type");
            String orderId = OrderUtil.getOrderNo();
            String names = (String) maps.get("names");
            Boolean bool = false;
            if(goBuy!=null && goBuy.equals("yes")){
                // 直接购买
                bool = goBuy(user_id, info, money, payment_type, orderId);
            }else{
                String ids = (String) maps.get("ids");
                // 添加订单
                bool = orderService.AddOrders(user_id, ids, new Date(), payment_type,orderId,info,money);
            }
            if(bool){
                // 支付
                Object pay = service.pay(names, Double.valueOf(money),orderId);
                if (pay != null) {
                    responseData = new ResponseData<Object>(true, pay, "支付成功");
                } else throw new RuntimeException("支付异常");
            }else throw new RuntimeException("支付异常");
        } catch (Exception e) {
            responseData = new ResponseData<Object>(false, e.getMessage());
        }
        return objectMapper.writeValueAsString(responseData);
    }


    private Boolean goBuy(String userId,String info,Integer money,String paymentType,String orderId){
        return orderService.AddOrder(userId, info, money, paymentType, orderId);
    }

    @PostMapping("/toPay")
    public String toPay(@RequestBody Map<String, Object> maps) throws JsonProcessingException {
        ResponseData<Object> responseData = null;
        try {
            String names = (String) maps.get("names");
            Integer money = (Integer) maps.get("money");
            Object order_id = maps.get("order_id");
            Object pay = service.pay(names, Double.valueOf(money), String.valueOf(order_id));
            if (pay != null) {
                responseData = new ResponseData<Object>(true, pay, "连接成功");
            } else throw new RuntimeException("支付异常");
        } catch (RuntimeException e) {
            responseData = new ResponseData<Object>(false, e.getMessage());
        }
        return objectMapper.writeValueAsString(responseData);
    }

    @PostMapping(value = "/fallback")
    public Object fallback(HttpServletRequest request) {
        Map<String, String> maps = convertRequestParamsToMap(request);
        String orderId = maps.get("out_trade_no");
        if(!orderId.equals("")&&orderId!=null){
            Integer integer = service.updateOrderState(orderId);
            if(integer!=1) throw new RuntimeException("订单异常");
        }
        return null;
    }

    @DeleteMapping("/cancelOrder")
    public String cancelOrder(@RequestParam Map<String, Object> maps) throws JsonProcessingException {
        ResponseData<Object> responseData = null;
        try {
            String userId = (String) maps.get("userId");
            String order_id = (String) maps.get("order_id");
            Integer count = orderService.delOrder(Integer.parseInt(userId),order_id);
            if(count==1){
                responseData = new ResponseData<Object>(true,"取消成功");
            } throw new RuntimeException("数据异常");
        } catch (Exception e) {
            responseData = new ResponseData<Object>(false,e.getMessage());
        }
        return objectMapper.writeValueAsString(responseData);
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
